package service;


import entity.mvc.Token;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * @program: SSM201759225309
 * @description:
 * @author: Xiaozhuoer
 * @create: 2021-05-15 19:19
 **/

@Service
@ContextConfiguration("classpath:applicationContext.xml")
public class TokenManageService {


    private RedisService redisService; //提供redis相关服务

    @Resource(name = "stringRedisTemplate")
    private StringRedisTemplate stringRedisTemplate; //还是null!!!!

//    ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
//    StringRedisTemplate stringRedisTemplate = (StringRedisTemplate) context.getBean("stringRedisTemplate");

    public TokenManageService() {
        this.redisService = new RedisService(stringRedisTemplate);
    }

    /**
     * 生成Token
     * @param type 0-用户 1-设备
     * @param userName 名字
     * @param passWord 密码
     * @return token
     */
    public Token CreateToken(int type, String userName, String passWord){
        Token token = new Token();
        //设置type 0-用户 1-设备
        token.setType(type);
        //根据用户名和密码生成token值,hashCode加密
        int tokenId = (userName + passWord).hashCode();
        System.out.println("tokenId = " + tokenId);
        token.setId(tokenId);
        //设置UUID
        token.setUuid(UUID.randomUUID().toString());
        //根据type、id生成tokenValue, MD5加密
        String tokenValue = DigestUtils.md5DigestAsHex((String.valueOf(type) + String.valueOf(tokenId)).getBytes());
        System.out.println("tokenValue = " + tokenValue);
        token.setTokenValue(tokenValue);
        //存入redis,过期时间30秒
        redisService.set(token.getUuid(), token.getTokenValue(), 30);
        return token;
    }

    /**
     * 鉴权
     * @param uuid
     * @return 无0-有1
     */
    public boolean CheckToken(String uuid){
        return redisService.hasKey(uuid);
    }

}
